#include "guish.hpp"
#include <stdarg.h>

const char *shellCommand = NULL;
bool isInteractive = true;
const char *scriptName = NULL;
const char *command = NULL;
char **scriptArgV = NULL;
int scriptArgC = 0;

void handleArgs(int argc, char **argv)
{
	traceOutputName = "guish.log";
	
	shellCommand = argv[0];
	
	for(int ii=1; ii<argc; ii++)
	{
		string arg = argv[ii];
		
		if(arg == "-v" || arg == "--version") {
			printVersion();
			exit(0);
		} else if(arg == "-h" || arg == "-help" || arg == "--help") {
			printHelpText();
			exit(0);
		}
#ifdef UNIT_TEST
		else if(arg=="--unit-test") {
			runTests();
			summarizeTests();
			exit(0);
		}
		else if(arg=="--tokenizer-test") {
			interactiveTokenizerTest();
			exit(0);
		}
		else if(arg=="--parser-test") {
			interactiveParserTest();
			exit(0);
		}
#endif
		else if(arg=="--trace") {
			ii++;
			if(ii >= argc)
				argumentError("--trace: option requires an argument");
			setAlwaysTrace(true);
			traceOutputName = argv[ii];
		} else if(arg == "-c") {
			ii++;
			if(ii >= argc)
				argumentError("-c: option requires an argument");
			isInteractive = false;
			command = argv[ii];
			scriptArgV = argv+ii+1;
			scriptArgC = argc-ii-1;
		} else if(arg[0]=='-') {
			argumentError("%s: invalid option", arg.c_str());
		} else {
			isInteractive = false;
			scriptName = argv[ii];
			scriptArgV = argv+ii;
			scriptArgC = argc-ii;
			break;
		}
	}
	
	trace << "guish started\n";
}

void printHelpText()
{
	printf(
	"guish is an interactive shell which works with the guiterm terminal.\n"
	"You cannot run guish directly from a different kind of terminal; run\n"
	"guiterm instead. However, you can run guish from inside ssh if the is\n"
	"output displayed in guiterm.\n"
	"\n"
	"Usage: guish [option]\n"
	"\n"
	" -h, --help     Display this help and exit\n"
	" -v, --version  Output version information and exit\n"
	"\n"
	"Report bugs to http://code.google.com/p/guishell/issues/entry\n"
	);
}

void printVersion()
{
	printf(
	"guishell %s\n"
	"\n"
	"Copyright (C) 2009 Jim Babcock\n"
	"This is free software; see the source for copying conditions.  There is NO\n"
	"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
		,PACKAGE_VERSION
	);
}

void argumentError(const char *fmt, ...)
{
	va_list arglist;
	va_start(arglist, fmt);
	std::string msg = retvprintf(fmt, arglist);
	va_end(arglist);
	
	fprintf(stderr, "%s: %s\n", shellCommand, msg.c_str());
	exit(1);
}

